package practice;

public class LinkReverse {
    public static void main(String[] args) {
        ListNode head = build(1, 2, 3, 4, 5);
        print(head);
        print(reverse(head));
    }

    static ListNode reverse(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode n = head, p = null;
        for(;;) {
            n = n.next;
            head.next = p;
            if(n == null)
                break;
            p = head;
            head = n;
        }
        return head;
    }

    static void print(ListNode head) {
        ListNode t = head;
        while(true) {
            System.out.print(t.val);
            if(t.next == null)
                break;
            System.out.print(" -> ");
            t = t.next;
        }
        System.out.println();
    }

    static ListNode build(int... arr) {
        ListNode head = null;
        for (int i = arr.length - 1; i >= 0; i--) {
            ListNode t = head;
            head = new ListNode(arr[i]);
            head.next = t;
        }
        return head;
    }

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
}
